package com.example.design.singleton;

/**
 * @ClassName Singleton9
 * @Description ThreadLocal单例,类似于DCL(Double-Check-Locking)
 * @Author Administrator
 * @Date 2020/5/7 12:16
 * @Version 1.0
 */
public class Singleton9 {

    private static Singleton9 instance;
    private static ThreadLocal<Singleton9> threadLocal = new ThreadLocal<>();
    private Singleton9(){}

    public static Singleton9 getInstance(){
        // 第一次检查：若线程第一次访问，则进入if语句块；
        // 否则，若线程已经访问过，则直接返回ThreadLocal中的值
        if(threadLocal.get() == null){
            synchronized (Singleton9.class){
                // 第二次检查：该单例是否被创建
                if(threadLocal.get() == null){
                    instance = new Singleton9();
                }
                // 将单例放入ThreadLocal中
                threadLocal.set(instance);
            }
        }
        return instance;
    }

    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Singleton9 s1 = Singleton9.getInstance();
        Singleton9 s2 = Singleton9.getInstance();
        s1.setName("zhangsan9");
        s2.setName("lisi9");
        System.out.println(s1.getName());
        System.out.println(s2.getName());
        System.out.println(s1.getName().equals(s2.getName()));
    }

}
